package com.situ.ssm.user.service.impl;

import com.situ.ssm.user.dao.UserDao;
import com.situ.ssm.user.pojo.User;
import com.situ.ssm.user.service.UserService;
import com.situ.ssm.util.ConfigUtil;
import com.situ.ssm.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * @Project :springssm
 * @Author : yun&bo
 * @Date 2020/12/17 11:15
 * @Version
 */
@Service("useService")
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    @Override
    public String doUploadAvatar(MultipartFile multipartFile, String realPath) {
        if (multipartFile.isEmpty()){
            String fileName = multipartFile.getOriginalFilename();
            StringBuilder filePath = new StringBuilder(ConfigUtil.PATH_AVATAR);
            System.out.println(filePath);
            filePath.append("/")
                    .append(Calendar.getInstance().getTimeInMillis())
                    .append(fileName.substring(fileName.lastIndexOf(".")));
            File toFile =new File(realPath+filePath);
           File parentFile =  toFile.getParentFile();
           if(parentFile.exists()){
               parentFile.mkdirs();
           }
            try {
                System.out.println(toFile.getAbsolutePath());
                multipartFile.transferTo(toFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return filePath.toString();
        }
        return null;
    }

    @Override
    public int doAddUSer(User user, String createBy ) {
        user.setUserPass(MD5Util.encode(user.getUserPass()));
        user.setLoginCount(0);
        user.setIsLock(User.IS_LOCK_NO);
        user.setActiveFlag(1);
        user.setCreateBy(createBy);
        user.setCreateDate(new Date());
        return userDao.save(user);
    }

    @Override
    public User userLogin(String userCode, String userPass) {
        return userDao.userLogin(userCode,MD5Util.encode(userPass));
    }


}
